package com.ruoyix.weblog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyix.common.helper.LoginHelper;
import com.ruoyix.common.utils.StringUtils;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyix.weblog.domain.vo.BlogCommentResVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyix.weblog.domain.bo.BlogCommentBo;
import com.ruoyix.weblog.domain.vo.BlogCommentVo;
import com.ruoyix.weblog.domain.BlogComment;
import com.ruoyix.weblog.mapper.BlogCommentMapper;
import com.ruoyix.weblog.service.IBlogCommentService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 文章评论Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-27
 */
@RequiredArgsConstructor
@Service
public class BlogCommentServiceImpl implements IBlogCommentService {

    private final BlogCommentMapper baseMapper;

    /**
     * 查询文章评论
     */
    @Override
    public BlogCommentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询文章评论列表
     */
    @Override
    public TableDataInfo<BlogCommentVo> queryPageList(BlogCommentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BlogComment> lqw = buildQueryWrapper(bo);
        Page<BlogCommentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    public List<BlogCommentResVo> getNestedComments(BlogCommentBo bo) {
        List<BlogCommentResVo> allComments = baseMapper.selectCommentResList(bo);

        List<BlogCommentResVo> newComments = baseMapper.selectCommentResList(bo);

        Map<Long, BlogCommentResVo> commentMap = new HashMap<>();
        allComments.forEach(comment -> commentMap.put(comment.getId(), comment));


        Map<Long, BlogCommentResVo> newCommentMap = new HashMap<>();
        newComments.forEach(comment -> newCommentMap.put(comment.getId(), comment));


        List<BlogCommentResVo> nestedComments = new ArrayList<>();
        allComments.forEach(comment -> {
            if (comment.getParentCommentId() == 0) {
                buildCommentTree(comment, commentMap);
                nestedComments.add(comment);
            }
        });

        nestedComments.sort(Comparator.comparing(BlogCommentResVo::getCreateTime));


//        -------------------------[评论内容两层化]-----------------------------------
        nestedComments.forEach(item->{
            List<BlogCommentResVo> childComments = item.getChildComments();
            // 存储 parentCommentId 的列表
            List<Long> parentCommentIds = new ArrayList<>();

            // 遍历每个顶层评论
            for (BlogCommentResVo comment : childComments) {
                dfs(comment, parentCommentIds);
            }

            List<BlogCommentResVo> children = new ArrayList<>();
            for (Long id :parentCommentIds){
                BlogCommentResVo blogCommentVo = newCommentMap.get(id);
                children.add(blogCommentVo);
            }
            item.setChildComments(children);


        });
//        -----------------去掉则为n层结构对应前台的comment-item-----------------------
        return nestedComments;
    }

    private void buildCommentTree(BlogCommentResVo comment, Map<Long, BlogCommentResVo> commentMap) {
        List<BlogCommentResVo> childComments = commentMap.values().stream()
            .filter(subComment -> Objects.equals(subComment.getParentCommentId(), comment.getId()))
            .sorted(Comparator.comparing(BlogCommentResVo::getCreateTime))
            .collect(Collectors.toList());

        childComments.forEach(subComment -> buildCommentTree(subComment, commentMap));
        comment.setChildComments(childComments);
    }



    private static void dfs(BlogCommentResVo comment, List<Long> parentCommentIds) {
        // 存储当前评论的 parentCommentId
        parentCommentIds.add(comment.getId());

        // 遍历所有子评论
        if (comment.getChildComments() != null) {
            for (BlogCommentResVo child : comment.getChildComments()) {
                dfs(child, parentCommentIds);
            }
        }
    }




//    public List<BlogCommentVo> getNestedComments() {
//        // 一次性查询所有评论
//        List<BlogCommentVo> allComments = this.queryList(new BlogCommentBo());
//
//        // 构建 ID -> BlogCommentVo 映射
//        Map<Long, BlogCommentVo> commentMap = new HashMap<>();
//        for (BlogCommentVo comment : allComments) {
//            commentMap.put(comment.getId(), comment);
//        }
//
//        // 构建树形结构
//        List<BlogCommentVo> nestedComments = new ArrayList<>();
//        for (BlogCommentVo comment : allComments) {
//            if (comment.getParentCommentId() == 0) {
//                buildCommentTree(comment, commentMap);
//                nestedComments.add(comment);
//            }
//        }
//
//        // 对根评论按时间排序
//        nestedComments.sort(Comparator.comparing(BlogCommentVo::getCreateTime));
//
//
//        List<BlogCommentVo> withoutJsonComment = formatComments(nestedComments);
//
//
//
//        return nestedComments;
//    }
//
//
//    private void buildCommentTree(BlogCommentVo comment, Map<Long, BlogCommentVo> commentMap) {
//        List<BlogCommentVo> childComments = new ArrayList<>();
//        for (BlogCommentVo subComment : commentMap.values()) {
//            if (subComment.getParentCommentId() == comment.getId()) {
//                buildCommentTree(subComment, commentMap);
//                childComments.add(subComment);
//            }
//        }
//        // 对子评论按时间排序
//        childComments.sort(Comparator.comparing(BlogCommentVo::getCreateTime));
//        comment.setChildComments(childComments);
//    }
//
//
//    private List<BlogCommentVo> formatComments(List<BlogCommentVo> comments) {
//        List<BlogCommentVo> commentVoList = new ArrayList<>();
//
//        for (BlogCommentVo comment : comments) {
//            comment.getChildComments().forEach(item->{
//                BlogCommentVo blogCommentVo = new BlogCommentVo();
//                List<BlogCommentVo> childComments = new ArrayList<>();
//                readChildComment(item, 1,childComments);
//                blogCommentVo.setChildComments(childComments);
//                commentVoList.add(blogCommentVo);
//            });
//        }
//        return commentVoList;
//    }
//
//    private void readChildComment(BlogCommentVo comment, int level, List<BlogCommentVo> commentVoList) {
//        commentVoList.add(comment);
//        // 打印子评论信息
//        if (comment.getChildComments() != null) {
//            for (BlogCommentVo child : comment.getChildComments()) {
//                readChildComment(child, level + 1,commentVoList); // 递归打印子评论，层级加一
//            }
//        }
//    }





    /**
     * 查询文章评论列表
     */
    @Override
    public List<BlogCommentVo> queryList(BlogCommentBo bo) {
        LambdaQueryWrapper<BlogComment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BlogComment> buildQueryWrapper(BlogCommentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BlogComment> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSource() != null, BlogComment::getSource, bo.getSource());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), BlogComment::getType, bo.getType());
        lqw.eq(bo.getParentCommentId() != null, BlogComment::getParentCommentId, bo.getParentCommentId());
        lqw.eq(bo.getUserId() != null, BlogComment::getUserId, bo.getUserId());
        lqw.eq(bo.getFloorCommentId() != null, BlogComment::getFloorCommentId, bo.getFloorCommentId());
        lqw.eq(bo.getParentUserId() != null, BlogComment::getParentUserId, bo.getParentUserId());
        lqw.eq(bo.getLikeCount() != null, BlogComment::getLikeCount, bo.getLikeCount());
        lqw.eq(StringUtils.isNotBlank(bo.getCommentContent()), BlogComment::getCommentContent, bo.getCommentContent());
        lqw.eq(StringUtils.isNotBlank(bo.getCommentInfo()), BlogComment::getCommentInfo, bo.getCommentInfo());
        lqw.orderByAsc(BlogComment::getCreateTime);
        return lqw;
    }

    /**
     * 新增文章评论
     */
    @Override
    public Boolean insertByBo(BlogCommentBo bo) {
        BlogComment add = BeanUtil.toBean(bo, BlogComment.class);
        add.setUserId(LoginHelper.getUserId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改文章评论
     */
    @Override
    public Boolean updateByBo(BlogCommentBo bo) {
        BlogComment update = BeanUtil.toBean(bo, BlogComment.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BlogComment entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除文章评论
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    public List<BlogComment> findListCommentsByParentId(List<BlogComment> comments,Long parentId){
        return comments.stream()
            .filter(comment -> comment.getParentCommentId() == parentId) // 过滤出parentId为1的评论
            .sorted(Comparator.comparing(BlogComment::getCreateTime)) // 按createTime排序
            .collect(java.util.stream.Collectors.toList());
    }
}
